﻿using Microsoft.ExtendedReflection.ComponentModel;
using Microsoft.ExtendedReflection.Logging;
using Microsoft.ExtendedReflection.Monitoring;
using Microsoft.ExtendedReflection.Utilities;
using Microsoft.ExtendedReflection.Utilities.Safe;
using Microsoft.VisualStudio.TestTools.Common;
using Microsoft.VisualStudio.TestTools.Execution;
using System;

namespace MolesVS2012.Host
{
    [Serializable]
    internal sealed class RunResultSyncLogger : ComponentBase, IService
    {
        private readonly RemotingEntityKind entityKind;
        private Guid runGuid;
        private IResultSink resultSink;

        public RunResultSyncLogger(RemotingEntityKind entityKind)
        {
            this.entityKind = entityKind;
        }

        protected override void Initialize()
        {
            base.Initialize();
            IRunContextManager service = this.GetService<IRunContextManager>();
            this.runGuid = service.RunGuid;
            this.resultSink = service.ResultSink;
            this.GetService<IEventLogSource>().LogHandler += new RemoteEventHandler<LogEventArgs>(this.eventLogSource_LogHandler);
        }

        private void eventLogSource_LogHandler(LogEventArgs e)
        {
            using (_ProtectingThreadContext.Acquire())
            {
                string messageText = SafeString.Format("[{0}] {1}", (object)e.Category.ToLowerInvariant(), (object)e.Message);
                if (e.Level < LogLevel.Error)
                    messageText = SafeString.Format("!{0}! {1}", (object)EnumHelper.FormatAsLowerInvariant<LogLevel>((int)e.Level), (object)messageText);
                this.resultSink.AddResult((TestMessage)new TestRunTextResultMessage(this.runGuid, messageText));
                Exception caughtException = e.CaughtException;
                if (caughtException == null)
                    return;
                this.resultSink.AddResult((TestMessage)new TestRunTextResultMessage(this.runGuid, SafeString.ToString((object)caughtException)));
            }
        }
    }
}
